package cn.dzz.springcloud.controller;

import cn.dzz.springcloud.component.JsonResult;
import cn.dzz.springcloud.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 22:47
 */

@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {
    // HttpClient & RestTemplate
    @Resource
    private RestTemplate restTemplate;

    // 单机单一模块调用  public static final String PAYMENT_URL = "http://localhost:8001";

    // 集群调用则使用共同的服务名称来实现
    public static final String PAYMENT_URL = "http://PROVIDER-PAYMENT-SERVICE";

    @GetMapping("consumer/payment/create")
    public JsonResult<Payment> createPayment(Payment payment) {
        log.info("消费者订单模块调用提供者支付模块的 createPayment");
        return  restTemplate.postForObject(
                PAYMENT_URL + "/payment/create", // 接口地址URL
                payment, // 请求参数对象
                JsonResult.class // JSON封装类的字节实例
        );
    }

    @GetMapping("consumer/payment/get/{id}") // order/consumer/payment/get/{id}
    public JsonResult<Payment> getPaymentById(@PathVariable("id") Long paymentId) {
        log.info("消费者订单模块调用提供者支付模块的 getPaymentById");
        return restTemplate.getForObject(
                PAYMENT_URL + "/payment/get/" + paymentId,
                JsonResult.class
        );
    }

    @PostMapping("consumer/payment/get/{id}")
    public JsonResult<Payment> getPaymentByIdAndPostMethod(@PathVariable("id") Long paymentId) {
        log.info("(Post方式请求)消费者订单模块调用提供者支付模块的 getPaymentById");
        ResponseEntity<JsonResult> jsonResultResponseEntity = restTemplate.getForEntity(
                PAYMENT_URL + "/payment/get/" + paymentId,
                JsonResult.class
        );

        if (jsonResultResponseEntity.getStatusCode().is2xxSuccessful()) return jsonResultResponseEntity.getBody();
        else return new JsonResult<>(444, "操作失败");
    }
}
